/*
 * Copyright (C) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

wave.ui.loadCss();

var stateAvailable = false;
var participantsReceived = false;

// Prefix userId with this so it's easy to search for this token.
var indexerFriendlyPrefix = "flag__";

// gadget state stored as alertees = "<flag__bob@google.com>,...." (CDL)
// this is so it's easy for the indexer to add a token to be searched on.

var candidates = [];  // list of objects with an id attribute and 
                      //     toString = first name.
var alerteeMap = {};  // backed by wave's gadget state, set in 
                      //     recalculateCandidates()

function AddAlertee(dropdown) {
  var idx = dropdown.selectedIndex - 1;   // -1 for the dummy "add"
  // add the candidate to the alertee list.
  var alertee = candidates[idx];
  var state = wave.getState();
  if (state) {
    var astr = state.get("alertees", "");
    astr += indexerFriendlyPrefix + alertee.pid + ",";
    state.submitValue("alertees", astr);

    wave.log("added: " + alertee.pid + " new state: " + astr);
  }

  recalculateCandidates();
  return true;
}

function RemoveAlertee(alerteeId) {
    var state = wave.getState();
    if (state) {
      var astr = state.get("alertees", "");
      // Delete the Id and separator.
      state.submitValue("alertees", astr.replace(indexerFriendlyPrefix + alerteeId + ",", ""));
      wave.log("removed: " + alerteeId);
    }

  recalculateCandidates();
  return true;
}

function render() {
  if (!isGadgetReady()) {
    return;
  }

  var candidate_str = "";
  for (var pid in candidates) {
    candidate_str += "<option>" + candidates[pid].toString() + "</option>";
  }
  var buttons = "";
  var viewerIsAlertee = false;
  for (var aid in alerteeMap) {
      var style = "\"font-weight:bold\"";
      var alerteeName = alerteeMap[aid];
      if (wave.getViewer().getId() == aid) {
        viewerIsAlertee = true;
        style = "\"color:#ff0000; font-size:150%\"";
        alerteeName = "yourself";
      }
      buttons += "<input type=\"button\" onclick=\"RemoveAlertee('" + aid + "')\"  style=" + style + " value=\"" + alerteeMap[aid] + "\" title=\"clear the flag for " + alerteeName + "\">";
    // TODO(jochen): See whether allowing everyone to modify the list (as code
    //               above does) is acceptable. If so, delete the following:
    //
    // if (wave.getViewer().getId() == aid) {
    //  viewerIsAlertee = true;
    //  // buttons += "<a type=\"button\" id=\"viewer_button\" onclick=\"RemoveAlertee('" + aid + "')\"  style=\"color:#ff0000; font-size:200%\"> "+ alerteeMap[aid] + "</a>";
    //  buttons += "<input type=\"button\" onclick=\"RemoveAlertee('" + aid + "')\"  style=\"color:#ff0000; font-size:150%\" value=\"" + alerteeMap[aid] + "\">";
    // } else {
    //  buttons += "&nbsp <span style=\"font-size:125%; font-weight:bold\">" + alerteeMap[aid] + "</span>";
    // }
  }

  // Create output:
  var out = "<table border=0><tr><td><font size=+3 " + (viewerIsAlertee ? "color=\"#FF0000\"" : "") + ">&#x2691;</font></td>";
  if (buttons != "") {
    out += "<td>" + buttons + "</td>";
  }
  if (candidate_str != "") {
    out += "<td>&nbsp<select id=\"mainform\" onchange=\"AddAlertee(this)\"><option>add</option>" + candidate_str + "</select></td>";
  }
  out += "</tr></table>";

  document.getElementById('gadget-div').innerHTML = out;
  //wave.ui.makeButton(document.getElementById('viewer_button'));
  gadgets.window.adjustHeight();
}


// TODO(jochen): do we remove alertees when they no longer appear in the participant list?
function recalculateCandidates() {
  participantsReceived = true;
  if (!isGadgetReady()) {
    return;
  }

  alerteeMap = {}  // clear.
  candidates = []  // clear.
  var arrP = wave.getParticipants();
  // All participants not in alertee list are candidates.

  var state = wave.getState();
  var alertees = state.get("alertees", "");
    wave.log("recalc: state = " + alertees);

  for (var i in arrP) {
    pid = arrP[i].getId();
    var p = {};
    p.pid = pid;
    p.firstname = arrP[i].getDisplayName().split(" ")[0];
    p.toString = function() { return this.firstname; }

    // Is the participant in the alertee map? If not, he's a candidate.
    if(alertees.search(pid) == -1) {
      candidates.push(p);
        wave.log("pushcandidate: " + p.pid);
    } else {
      alerteeMap[pid] = p;
        wave.log("map alertee: " + p.pid);
    }
  }
  candidates.sort();
  render();
}


function onStateChanged() {
  if (!isGadgetReady()) {
    if (wave.getState() != null) {
      stateAvailable = true;
      onStateChanged();
    }
    return;
  }
  recalculateCandidates();
}


/***** Gadget initialisation functions. *****/

function isGadgetReady() {
  return participantsReceived && stateAvailable;
}

gadgets.util.registerOnLoadHandler(function() {
  wave.setParticipantCallback(recalculateCandidates);
  wave.setStateCallback(onStateChanged);
});

google.setOnLoadCallback(function() {
  if (isGadgetReady()) {
      onStateChanged();
  }
});
